//
//  WLRegisterController.m
//  WanLian
//
//  Created by muzhuang on 2018/9/11.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRegisterController.h"
#import "WLRouterBingFlowController.h"
#import "WLWebViewController.h"

@interface WLRegisterController ()<UITextFieldDelegate>
{
    int resendCodeTime;
    UIButton *btnAgree;
}

@property (nonatomic, strong) UITextField *textRegPhone;
@property (nonatomic, strong) UITextField *textRegCode;
@property (nonatomic, strong) UIButton      *btnRegCode;
@property (nonatomic, strong) UIButton      *btnReg;
@property (nonatomic, strong) NSTimer       *regTimer;

@end

@implementation WLRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    
    UIButton *backBtn = [[UIButton alloc] init];
    [backBtn setImage:[UIImage imageNamed:@"arrow_back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backBtn addTarget:self action:@selector(backFromRegister) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    WLWkSelf
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).offset(16);
        make.top.equalTo(weakSelf.view.mas_top).offset(WL_StatusBarHeight);
        make.size.mas_equalTo(CGSizeMake(80, 44));
    }];
    
    UILabel *labReg = [[UILabel alloc] init];
    labReg.font = [WLCommonTool fontTypePingFangSCMedium:24];
    labReg.textColor = wlDarkGrayColor;
    labReg.text = @"注册";
    [self.view addSubview:labReg];
    [labReg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(WLScaleX(82));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(32));
    }];
    
    UILabel *labTip = [[UILabel alloc] init];
    labTip.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labTip.textColor = wlDarkGrayColor;
    [self.view addSubview:labTip];
    NSMutableAttributedString *strTip = [[NSMutableAttributedString alloc] initWithString:@"天翼链路由器 是一款可以赚钱的家庭智能路由器"];
    [strTip addAttribute:NSFontAttributeName
                       value:[WLCommonTool fontTypePingFangSCMedium:14]
                       range:NSMakeRange(0, 6)];
    labTip.attributedText = strTip;
    [labTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(WLScaleX(130));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(32));
    }];
    
    _textRegPhone = [[UITextField alloc] init];
    _textRegPhone.keyboardType = UIKeyboardTypeNumberPad;
    _textRegPhone.borderStyle = UITextBorderStyleNone;
    _textRegPhone.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textRegPhone.delegate = self;
    _textRegPhone.placeholder = @"请输入您的手机号";
    [self.view addSubview:_textRegPhone];
    [_textRegPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(WLScaleX(200));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(32));
        make.right.equalTo(weakSelf.view.mas_right).offset(-WLScaleX(32));
        make.height.equalTo(@(WLScaleX(40)));
    }];
    
    UIView *phoneLine = [[UIView alloc] init];
    phoneLine.backgroundColor = wlUnderlineColor;
    [self.view addSubview:phoneLine];
    [phoneLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.textRegPhone);
        make.top.equalTo(weakSelf.textRegPhone.mas_bottom);
        make.height.equalTo(@(WLScaleX(1)));
    }];
    
    _textRegCode = [[UITextField alloc] init];
    _textRegCode.borderStyle = UITextBorderStyleNone;
    _textRegCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textRegCode.delegate = self;
    _textRegCode.keyboardType = UIKeyboardTypeNumberPad;
    _textRegCode.placeholder = @"请输入短信验证码";
    [self.view addSubview:_textRegCode];
    [_textRegCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(weakSelf.textRegPhone);
        make.top.equalTo(weakSelf.textRegPhone.mas_bottom).offset(WLScaleX(10));
        make.width.equalTo(@(WLScaleX(206)));
    }];
    
    UIView *verticalLine = [[UIView alloc] init];
    verticalLine.backgroundColor = wlUnderlineColor;
    [self.view addSubview:verticalLine];
    [verticalLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.textRegCode.mas_top).offset(WLScaleX(10));
        make.left.equalTo(weakSelf.view.mas_left).offset(WLScaleX(240));
        make.size.mas_equalTo(CGSizeMake(WLScaleX(1), WLScaleX(20)));
    }];
    
    _btnRegCode = [[UIButton alloc] init];
    _btnRegCode.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:16];
    [_btnRegCode setTitleColor:wlUIColorRGB(0x1A59E2) forState:UIControlStateNormal];
    _btnRegCode.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_btnRegCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_btnRegCode addTarget:self action:@selector(getRegCodeAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnRegCode];
    [_btnRegCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(verticalLine.mas_right).offset(WLScaleX(2));
        make.top.equalTo(weakSelf.textRegCode.mas_top);
        make.bottom.equalTo(weakSelf.textRegCode.mas_bottom);
        make.right.equalTo(weakSelf.textRegPhone.mas_right);
    }];
    
    
    UIView *textLine = [[UIView alloc] init];
    textLine.backgroundColor = wlUnderlineColor;
    [self.view addSubview:textLine];
    [textLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.textRegPhone);
        make.top.equalTo(weakSelf.textRegCode.mas_bottom);
        make.height.equalTo(@(WLScaleX(1)));
    }];
    
    _btnReg = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL-WLScaleX(62), WLScaleX(47))];
    CAGradientLayer *gradientBtn = [CAGradientLayer layer];
    gradientBtn.frame = _btnReg.bounds;  // 设置显示的frame
    gradientBtn.colors = @[(__bridge id)wlUIColorRGB(0x1A59E2).CGColor,(__bridge id)wlUIColorRGB(0x2292F5).CGColor]; // 设置渐变颜色
    gradientBtn.startPoint = CGPointMake(0, 0);
    gradientBtn.endPoint = CGPointMake(1, 0);
    [_btnReg.layer insertSublayer:gradientBtn atIndex:0];
    
    _btnReg.layer.cornerRadius = 5;//WLScaleX(5);
    _btnReg.layer.masksToBounds = YES;
    //    [_btnReg setBackgroundColor:wlUnderlineColor];
    _btnReg.titleLabel.font = [WLCommonTool fontTypePingFangSCMedium:16];
    [_btnReg setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnReg setTitle:@"注册" forState:UIControlStateNormal];
    [_btnReg addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnReg];
    [_btnReg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.textRegCode.mas_bottom).offset(WLScaleX(40));
        make.left.right.equalTo(weakSelf.textRegPhone);
        make.height.equalTo(@(WLScaleX(47)));
    }];
    //    _btnReg.enabled = NO;
    
//    UIButton *btnAgree = [[UIButton alloc] init];
//    [btnAgree setImage:[UIImage imageNamed:@"agree_btn"] forState:UIControlStateNormal];
//    btnAgree.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:12];
//    [btnAgree setTitleColor:wlLightTextColor forState:UIControlStateNormal];
//    [btnAgree setTitle:@" 已阅读并同意《用户服务协议》" forState:UIControlStateNormal];
//    [btnAgree addTarget:self action:@selector(agreeRegAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btnAgree];
//    [btnAgree mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(weakSelf.btnReg.mas_bottom).offset(WLScaleX(15));
//        make.centerX.equalTo(weakSelf.view.mas_centerX);
//    }];
    CGFloat left = (WIDTH_SCREEN_WL-175-30)/2.0;//labwidth大约是175
    btnAgree = [[UIButton alloc] init];
    [btnAgree setImage:[UIImage imageNamed:@"disagree_btn"] forState:UIControlStateNormal];
    [btnAgree setImage:[UIImage imageNamed:@"agree_btn"] forState:UIControlStateSelected];
    [btnAgree addTarget:self action:@selector(agreeRegAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAgree];
    btnAgree.selected = YES;
    [btnAgree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.btnReg.mas_bottom).offset(WLScaleX(10));
        //        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.left.equalTo(weakSelf.view.mas_left).offset(left);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    UIButton *btnAgreement = [[UIButton alloc] init];
    btnAgreement.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:12];
    [btnAgreement setTitleColor:wlLightTextColor forState:UIControlStateNormal];
    [btnAgreement setTitle:@"已阅读并同意《用户服务协议》" forState:UIControlStateNormal];
    [btnAgreement addTarget:self action:@selector(agreementAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAgreement];
    [btnAgreement mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.btnReg.mas_bottom).offset(WLScaleX(15));
        //        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.left.equalTo(weakSelf.view.mas_left).offset(left+30);
        make.height.equalTo(@(20));
    }];
}

- (void)backFromRegister
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getRegCodeAction
{
    if ([WLCommonTool isMobileNumber:_textRegPhone.text]==NO) {
        [self showHUDMessage:@"请输入正确的手机号"];
        return;
    }
    resendCodeTime = 60;
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"valitation/msg/code" withParamsDic:@{@"mobile":_textRegPhone.text} success:^(NSDictionary *successDict) {
        if (weakSelf.regTimer == nil)
        {
            weakSelf.regTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timingCodeAction) userInfo:nil repeats:YES];
            [weakSelf.btnRegCode setTitleColor:wlLightTextColor forState:UIControlStateNormal];
            weakSelf.btnRegCode.userInteractionEnabled = NO;
        }
        NSString *strMsg = successDict[@"message"];
        if (strMsg != nil&&[strMsg isKindOfClass:[NSNull class]]==NO)
        {
            [weakSelf showHUDMessage:strMsg];
        }
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)timingCodeAction
{
    resendCodeTime -= 1;
    NSString *string = [NSString stringWithFormat:@"%ds",resendCodeTime];
    [self.btnRegCode setTitle:string forState:UIControlStateNormal];
    if (resendCodeTime < 1) {
        [self.btnRegCode setTitle:@"重新发送" forState:UIControlStateNormal];
        self.btnRegCode.userInteractionEnabled = YES;
        [self.btnRegCode setTitleColor:wlUIColorRGB(0x1A59E2) forState:UIControlStateNormal];
        resendCodeTime = 60;
        [_regTimer invalidate];
        _regTimer = nil;
    }
}
/*
bresult = 1;
count = 0;
errorTag = 0;
message = "<null>";
object =     {
    birthday = "<null>";
    email = "<null>";
    enable = 1;
    headimg = "<null>";
    id = 50;
    lastLoginTime = "<null>";
    lastUpdateTime = 1537430696000;
    phone = 15617685591;
    remark = "<null>";
    sex = "<null>";
    upassword = 978717;
    username = "<null>";
};
url = "<null>";*/
- (void)registerAction
{
    if ([WLCommonTool isMobileNumber:_textRegPhone.text]==NO) {
        [self showHUDMessage:@"请输入正确的手机号"];
        return;
    }
    if (_textRegCode.text.length<6) {
        [self showHUDMessage:@"请输入正确的验证码"];
        return;
    }
    if (btnAgree.selected==NO) {
        [self showHUDMessage:@"请阅读并同意用户服务协议"];
        return;
    }
    [self.view endEditing:YES];
    NSDictionary *params = @{@"mobile":_textRegPhone.text,@"code":_textRegCode.text};
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/register/mobile" withParamsDic:params success:^(NSDictionary *successDict) {
        WLUserInfo *user = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:user];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        if (user.sessionId !=nil)
        {
            [userDefaults setObject:user.sessionId forKey:USER_SESSION];
        }
        if (user.phone !=nil) {
            [userDefaults setObject:user.phone forKey:USER_PHONE];
        }
        [userDefaults synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:kNOTIFICATION_LOGINED object:nil];
        [weakSelf goToBingding];
//        [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)agreeRegAction:(UIButton *)agreeBtn
{
    btnAgree.selected = !btnAgree.selected;
}

- (void)agreementAction
{
    WLWebViewController *webView = [[WLWebViewController alloc] init];
    webView.urlStr = [NSString stringWithFormat:@"%@/help/agreement.html",[WLCommonTool getWebHost]];
    webView.titleStr = @"用户服务协议";
    [self.navigationController pushViewController:webView animated:YES];
}

- (void)goToBingding
{
    WLRouterBingFlowController *flowController = [[WLRouterBingFlowController alloc] init];
    flowController.isPresented = YES;
    flowController.isPopDisabled = YES;
    [self.navigationController pushViewController:flowController animated:YES];
}

#pragma mark - UITextDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField isEqual:_textRegCode]) {
        if (textField.text.length >= 6 && string.length != 0) {
            return NO;
        }
    }
    if ([textField isEqual:_textRegPhone]) {
        if (textField.text.length >= 11 && string.length != 0) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
